var ACCOUNTING = {
	
	g_payment_methods: [],
	g_payment_method_details: [],
	g_acctg_receipts: [],
	g_acctg_receipt_details: [],
	
	// New Entry Global Variables
	g_money_in_cntr  : 1,
	g_money_out_cntr : 1,
	g_other_cntr     : 1,
	
	g_money_in_str   : "MONEY_IN_",
	g_money_out_str  : "MONEY_OUT_",
	g_other_str      : "OTHER_",
	
	//Display error message
	show_error_message : function(error_message) {
			COMMON.show_notification('#message-box','box-error',error_message,null);
			//$('.popup_new_person .loader').hide();
	},
	
	//Display error message
	show_info_message : function(info_message) {
			COMMON.show_notification('#message-box','box-info',info_message,null);
			//$('.popup_new_person .loader').hide();
	}
			
};

$(function(){	

	/****************** New Entry View Functions ******************/
	
	//Select Entry Options
	$("#select-new-entry-option").change(function(){
		$selected = $("#select-new-entry-option option:selected").val();
		if($selected == 'with_po_rfq')
		{
			$("#option-existing-po-box").show('slow');
		}
		else if($selected == 'no_po_rfq')
		{
			$("#option-existing-po-box").hide('slow');
		}
	});
	
	//Select Specific Account based on Account Group
	$(".select-accounts").live('change',function(){
		$selected = $(".select-accounts option:selected").val();
		
		//Show specific accounts
		$(".accounts").hide();
		$("#" + $selected).show();
	});
	
	//Sets ID for the Money In and Money Out cloned components
	var set_element_id_to_components = function(newElement, elementId, isOther) {
		
		//Transaction Date
//		var strDate = "";

		newElement.find(".field-transaction-date").attr("id", "field-transaction-date_" + elementId).datepick();
		newElement.find(".transaction-date-box").attr("id", "transaction-date-box_" + elementId).datepick();
		//alert('done setting transaction date');
//TODO
//		{
//		   onSelect: function(dateText, inst) { 
//			  var dateAsString = "" + dateText; //the first parameter of this function
//			  var dateAsObject = $(this).datepick( 'getDate' ); //the getDate method
//			  var date = new Date(dateAsString);
//			  
//			  strDate = "" + date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
//			  //alert(dateAsObject.getDate());
//			  //var arrStr = dateAsString.split(" ");
//			  //alert(arrStr);
//			  alert(strDate);
//			  //$.datepicker.parseDate("dd MM yyyy", dateAsObject);
//			  
//			  var componentId = $(this).attr("id");
//			  $("#field-transaction-date_" + componentId.substring( componentId.indexOf("_") + 1 )).val() = strDate;
//		   }
//		});
//		
//		newElement.find(".transaction-date-box").live("click", function(){
//			var componentId = $(this).attr("id");
//			
//			var value = $("#transaction-date-box_" + componentId.substring( componentId.indexOf("_") + 1 )).val();
//			alert(value);
//		});
		
		if(!isOther) {

			//Set the IDs for the particular classes
			newElement.find(".label-transaction-identifier").attr("id", "label-transaction-identifier_" + elementId);
			newElement.find(".hide-show-title").attr("id", "hide-show-title_" + elementId);
			newElement.find(".hide-show-money-in-out").attr( "id", "hide-show-money-in-out_" + elementId );
			newElement.find(".image-hide-show").attr( "id", "image-hide-show_" + elementId );
			newElement.find(".delete-money-in-out").attr( "id", "delete-money-in-out_" + elementId );
			newElement.find(".transaction-details").attr( "id", "transaction-details_" + elementId );
			
			//alert('done setting hide show delete');
			
			//Amount
			//Add specific id for each component
			newElement.find(".field-amount-before-vat").attr("id", "field-amount-before-vat_" + elementId);
			newElement.find(".field-vat").attr("id", "field-vat_" + elementId);
			newElement.find(".field-withholding-tax").attr("id", "field-withholding-tax_" + elementId);
			newElement.find(".field-total-amount").attr("id", "field-total-amount_" + elementId);
			
			//Methods of Payment
			var payment_method_dashed = "";
			for( payment_method_id in g_payment_methods ) {		
				//Sample result is "payment-method-cash"	
				payment_method_dashed = "payment-method-" + g_payment_methods[payment_method_id].toLowerCase().replace(" ", "-");
				
				//Add id and name for the cloned radio components
				newElement.find("." + payment_method_dashed).attr( "id", payment_method_dashed + "_" + elementId ).attr( "name", "payment_method_" + elementId );
				
				//Add class and id for hideable details per method type
				newElement.find("." + payment_method_dashed + "-details").addClass( "payment-hideables_" + elementId ).attr( "id", payment_method_dashed + "-details_" + elementId );
				
				//Add event handler to this radio button
				newElement.find("." + payment_method_dashed).live('change', function(){	
				
					//Get the element ID sample "payment-method-cash_MONEY_IN_1"
					var componentId = $(this).attr("id");
					
					//Hide other details not related to the selected method
					$(".payment-hideables_" + componentId.substring( componentId.indexOf("_") + 1 )).hide();
					
					//Show only the details of the selected method
					$("#" + componentId.substring( 0, componentId.indexOf("_") ) + "-details_" + componentId.substring( componentId.indexOf("_") + 1 ) ).show();
					
				});
				
				//Payment Method Details
				for( payment_method_detail_id in g_payment_method_details[payment_method_id] ) {
					newElement.find(".field-method-detail-"+ payment_method_detail_id).attr("id", "field-method-detail-"+ payment_method_detail_id +"_" + elementId);
				}
			}
		}
		
		//Receipt Used in Transaction
		var acctg_receipt_dashed = "";
		for( acctg_receipt_id in g_acctg_receipts ) {		
		    //Sample result is "radio-receipt-official-receipt"	
			acctg_receipt_dashed = "receipt-" + g_acctg_receipts[acctg_receipt_id].toLowerCase().replace(" ", "-");
			
			//Add id and name for the cloned radio components
			newElement.find("." + acctg_receipt_dashed).attr( "id", acctg_receipt_dashed + "_" + elementId ).attr( "name", "acctg_receipt_" + elementId );
			
			//Add class and id for hideable details per receipt type
			newElement.find("." + acctg_receipt_dashed + "-details").addClass( "receipt-hideables_" + elementId ).attr( "id", acctg_receipt_dashed + "-details_" + elementId );
			
			//Add event handler to this radio button
			newElement.find("." + acctg_receipt_dashed).live('change', function(){	
			
				//Get the element ID sample "radio-receipt-official-receipt_MONEY_IN_1"
				var componentId = $(this).attr("id");
				
				//Hide other details not related to the selected receipt
				$(".receipt-hideables_" + componentId.substring( componentId.indexOf("_") + 1 )).hide();
				
				//Show only the details of the selected receipt
				$("#" + componentId.substring( 0, componentId.indexOf("_") ) + "-details_" + componentId.substring( componentId.indexOf("_") + 1 ) ).show();
				
			});
			
			//Receipt Details
			acctg_receipt_detail_type = "";
			for( acctg_receipt_detail_id in g_acctg_receipt_details[acctg_receipt_id] ) {
				for( acctg_receipt_detail_name in g_acctg_receipt_details[acctg_receipt_id][acctg_receipt_detail_id]) {
					acctg_receipt_detail_type = g_acctg_receipt_details[acctg_receipt_id][acctg_receipt_detail_id][acctg_receipt_detail_name];
					
					//Add id based on detail type 
					if( acctg_receipt_detail_type == 'text' ) {
						newElement.find(".field-receipt-detail-"+ acctg_receipt_detail_id).attr("id", "field-receipt-detail-"+ acctg_receipt_detail_id +"_" + elementId);
					}
					else if( acctg_receipt_detail_type == 'checkbox' ) {
						newElement.find(".checkbox-receipt-detail-"+ acctg_receipt_detail_id).attr("id", "checkbox-receipt-detail-"+ acctg_receipt_detail_id +"_" + elementId);
					}
				}
			}
		}
		
		//Attachment
		newElement.find(".file-attachement").attr("id", "file-attachment_" + elementId).attr("name", "attachment_" + elementId);
		newElement.find(".transaction-attachment-box").attr("id", "transaction-attachment-box_" + elementId);		
		newElement.find(".attachment-buttons").attr("id", "attachment-buttons_" + elementId);
		newElement.find(".button-add-attachment").attr("id", "button-add-attachment_" + elementId);
		newElement.find(".button-remove-attachment").attr("id", "button-remove-attachment_" + elementId);
//TODO		
//		newElement.find(".file-attachement").live('change', function(){
//			
//			//Get the element ID - "file-attachment_MONEY_IN_1"
//			var componentId = $(this).attr("id");
//			
//			//Show add and remove buttons
//			$("#attachment-buttons_" + componentId.substring( componentId.indexOf("_") + 1 )).show();
//		});
		
		//Transaction Identifier
		newElement.find(".select-identifier").attr("id", "select-identifier_" + elementId);
		
		//Transaction Note
		newElement.find(".field-transaction-note").attr("id", "field-transaction-note_" + elementId);
		 
		//Add transaction
		newElement.prependTo(".transactions").show('slow');
	}
	
	//Add Money In
	$("#button-add-money-in").click(function(){
		 //Create new element ID - MONEY_IN<count>
		var elementId = ACCOUNTING.g_money_in_str + "" + ACCOUNTING.g_money_in_cntr;
		//alert(elementId);
		
		//Create new element from the template
		var newElement = $("#money-in-out-box").clone(true).attr( "id", elementId );
		//alert('Done cloning');
		
		//Set ID for the cloned components
		var isOther = false;
		newElement.find("#money-in-out-title").html( "Money In (Receivable)");
		set_element_id_to_components(newElement, elementId, isOther);
		//alert("DONE setting");
		
		//Increment count
		ACCOUNTING.g_money_in_cntr++;
		
		return false;
	});
	
	//Add Money Out
	$("#button-add-money-out").click(function(){
		//Create new element ID - MONEY_OUT<count>
		var elementId = ACCOUNTING.g_money_out_str + "" + ACCOUNTING.g_money_out_cntr;
		
		//Create new element from the template
		var newElement = $("#money-in-out-box").clone(true).attr( "id", elementId );
		
		//Set ID for the cloned components
		var isOther = false;
		newElement.find("#money-in-out-title").html( "Money Out (Payable)");
		set_element_id_to_components(newElement, elementId, isOther);
		
		//Increment count
		ACCOUNTING.g_money_out_cntr++;
		
		return false;
	});
	
	//Add Other
	$("#button-add-other").click(function(){
		//Create new element ID - OTHER<count>
		var elementId = ACCOUNTING.g_other_str + "" + ACCOUNTING.g_other_cntr;
		
		//Create new element from the template
		var newElement = $("#other-box").clone(true).attr( "id", elementId );
		
		//Set the IDs for the particular classes
		newElement.find(".label-transaction-identifier").attr("id", "label-transaction-identifier_" + elementId);
		newElement.find(".hide-show-title").attr("id", "hide-show-title_" + elementId);
		newElement.find(".hide-show-other").attr("id", "hide-show-other_" + elementId);
		newElement.find(".image-hide-show").attr( "id", "image-hide-show_" + elementId );
		newElement.find(".delete-other").attr("id", "delete-other_" + elementId);
		newElement.find(".transaction-details").attr("id", "transaction-details_" + elementId );
		
		//Set ID for the cloned components
		var isOther = true;
		set_element_id_to_components(newElement, elementId, isOther);
		
		//Add transaction
		newElement.prependTo(".transactions").show();
		
		//Increment count
		ACCOUNTING.g_other_cntr++;
		
		return false;
	});
	
	//Hide Money In or Out
	$(".hide-show-money-in-out").live("click", function(){
		var elementId = $(this).attr("id");
		var transactionDetails = "transaction-details_";
		
		//Get the element ID and append it to the particular elements
		elementId = elementId.substring(elementId.indexOf("_")+1);
		hideShowTitle = hideShowTitle + elementId;
		transactionDetails = transactionDetails + elementId;
		
		var hideShowTitle = $("#hide-show-money-in-out_" + elementId).attr("title");
		var transaction_identifier = $("#select-identifier_" + elementId +" option:selected").text();		
		if( hideShowTitle == 'Hide' ) {
			$("#"+transactionDetails).hide(0);
			$("#hide-show-money-in-out_" + elementId).attr("title", "Show");
			$("#image-hide-show_" + elementId).attr("src", COMMON.base_url+"webroot/images/icons/bullet_arrow_down.png");
			$("#label-transaction-identifier_" + elementId).html(transaction_identifier);
		}
		else {
			$("#"+transactionDetails).show('slow');
			$("#hide-show-money-in-out_" + elementId).attr("title", "Hide");
			$("#image-hide-show_" + elementId).attr("src", COMMON.base_url+"webroot/images/icons/bullet_arrow_up.png");
			$("#label-transaction-identifier_" + elementId).html("");
		}
		
		//Focus the element
		$(this).attr("href", "#hide-show-money-in-out_" + elementId );
	});
	
	//Hide Other
	$(".hide-show-other").live("click", function(){
		var elementId = $(this).attr("id");
		var transactionDetails = "transaction-details_";
		
		//Get the element ID and append it to the particular elements
		elementId = elementId.substring( elementId.indexOf("_") + 1 );
		hideShowTitle = hideShowTitle + elementId;
		transactionDetails = transactionDetails + elementId;
		
		var hideShowTitle = $("#hide-show-other_" + elementId).attr("title");
		var transaction_identifier = $("#select-identifier_" + elementId +" option:selected").text();		
		if( hideShowTitle == 'Hide' ) {
			$("#"+transactionDetails).hide(0);
			$("#hide-show-other_" + elementId).attr("title", "Show");
			$("#image-hide-show_" + elementId).attr("src", COMMON.base_url+"webroot/images/icons/bullet_arrow_down.png");
			$("#label-transaction-identifier_" + elementId).html(transaction_identifier);
		}
		else {
			$("#"+transactionDetails).show('slow');
			$("#hide-show-other_" + elementId).attr("title", "Hide");
			$("#image-hide-show_" + elementId).attr("src", COMMON.base_url+"webroot/images/icons/bullet_arrow_up.png");
			$("#label-transaction-identifier_" + elementId).html("");
		}
		
		//Focus the element
		$(this).attr("href", "#hide-show-other_" + elementId );
	});
	
	//Delete Money In or Out
	$(".delete-money-in-out").live("click", function(){
		//Get the element ID and remove
		var elementId = $(this).attr("id");		
		elementId = elementId.substring(elementId.indexOf("_")+1);
		$("#"+elementId).remove();
	});
	
	//Delete Other
	$(".delete-other").live("click", function(){
		//Get the element ID and remove
		var elementId = $(this).attr("id");		
		elementId = elementId.substring(elementId.indexOf("_")+1);
		$("#"+elementId).remove();
	});
	
	//Add Attachment
	$(".button-add-attachment").live("click", function(){
		//Get the element ID and append to attachments
		var elementId = $(this).attr("id");	
		elementId = elementId.substring(elementId.indexOf("_")+1);
		$("#transaction-attachment-box_" + elementId).clone(true).appendTo(".transaction-attachments").show();
	});
	
	//Create New Entry
	$("#button-create-entry").live('click', function(){
		
		//show "loading" animation
		$('.button-create-entry .loader').show();
		
		//hide notification box
		COMMON.hide_notification('#message-box');	
						
		//Delete all previous transactions
		$('.transactions').find('.transaction').each( function(){
			//get transaction id
			transaction_id = $(this).closest('div').remove();
		});
		
		//check required fields
		if( $("#field-po-rfq-num").val() == "" && 
		    $("#select-new-entry-option option:selected").val() == 'with_po_rfq' )
		{
			//display error message
			ACCOUNTING.show_error_message('PO # or RFQ # is required.');
		}
		else
		{		
			//prepare the data to be sent
			var form_data = {};
			form_data['selected_option'] = $("#select-new-entry-option option:selected").val();
			form_data['po_rfq_num'] = $('#field-po-rfq-num').val();
			form_data = { 'json':JSON.stringify(form_data) }
			
			//send the data
			$.ajax({
				type: 'POST',
				url: COMMON.base_url + 'accounting/create_new_entry',
				data: form_data,
				dataType: 'json',
				success: function(return_data) {
					if (return_data) {
						
						console.log(return_data.selected_option);
						if( return_data.selected_option=='with_po_rfq' ) {
							
							//Work ID
							$('.field-work-id').val(return_data.work_id);
							
							//Company Name
							$('.label-company-name').html(return_data.company_name);
							
							//PO #s and RFQ #s
							$('.label-po-num').html(return_data.customer_po_num);
							$('.label-rfq-num').html(return_data.customer_rfq_num);
							$('.label-new-po-num').html(return_data.new_po_num);
							$('.label-new-rfq-num').html(return_data.new_rfq_num);
							
							//Show form header
							$("#form-header").show();
						}
						else {
							//Hide form header
							$("#form-header").hide();
						}
						
						//Description
						$('.field-description').val(return_data.description);
						
						//Account Group
						var html_account_group = "<select class='select-accounts' name='account_group'>";
						html_account_group += "<option value='-1'>Select Account Group</option>";
						for (id in return_data.account_group) {
							html_account_group += "<option value='"+ id +"'>"+ return_data.account_group[id] +"</option>";
						}
						html_account_group += "</select>";
						$('.select-account-group').html(html_account_group);
						
						//Specific Accounts
						//console.log(return_data.acctg_accounts);
						var html_specific_accounts = "";
						for( account_group_id in return_data.acctg_accounts ) {
							html_specific_accounts += "<div id='"+ account_group_id +"' class='accounts hidden'>";
							html_specific_accounts += "<select class='"+ account_group_id +"' name='acctg_account_"+ account_group_id +"'>";
							html_specific_accounts += "<option value='-1'>Select Specific Account</option>";
							for( account_id in return_data.acctg_accounts[account_group_id] ) {
								html_specific_accounts += "<option value='"+ account_id +"'>"+ return_data.acctg_accounts[account_group_id][account_id] +"</option>";
							}
							html_specific_accounts += "</select>";
							html_specific_accounts += "</div>";
						}
						html_specific_accounts += "</select>";
						$('.specific-accounts').html(html_specific_accounts);	
						
						//Payment Methods
						var payment_method_name = "";
						var payment_method_name_lower_case = "";
						var payment_method_detail_name = "";
						
						//Save a global copy for the payment methods and details
						g_payment_methods = return_data.payment_methods;
						g_payment_method_details = return_data.payment_method_details;
						
						//Compose html 
						var html_payment_methods = "<table class='no-style-no-border full'  style='margin:0px 5px 0px 5px'>";
						html_payment_methods += "<tbody><tr><td colspan='2'><label>Method of Payment</label></td></tr>";
						
						for( payment_method_id in return_data.payment_methods ) {
							//Set payment method name
							payment_method_name = return_data.payment_methods[payment_method_id];
							payment_method_name_lower_case = payment_method_name.toLowerCase();
							
							html_payment_methods += "<tr><td><label class='choice'>";
							html_payment_methods += "<input type='radio' class='payment-method-" + payment_method_name_lower_case + "' value='" + payment_method_id + "' /> " + payment_method_name;
							html_payment_methods += "</label></td>";
							
							//Set payment method details
							html_payment_methods += "<td><div class='payment-method-"+ payment_method_name_lower_case +"-details hidden'>";
							for( payment_method_detail_id in return_data.payment_method_details[payment_method_id] ) {
								//alert(payment_method_detail_id);
								payment_method_detail_name =  return_data.payment_method_details[payment_method_id][payment_method_detail_id];								
								html_payment_methods += "<input class='field-method-detail-"+ payment_method_detail_id +"' type='text' value='"+ payment_method_detail_name +"' /><br />";								
							}
							html_payment_methods += "</div></td></tr>";
						}
						html_payment_methods += "</tbody></table>";
						
						//Display html
						$('.payment-methods').html(html_payment_methods);
						
						//Transaction Receipts
						var acctg_receipt_name = "";
						var acctg_receipt_name_dashed = "";
						var acctg_receipt_detail_name = "";
						var acctg_receipt_detail_name_underscored = "";
						var acctg_receipt_detail_type = "";
						
						//Save a global copy for the receipts used and details
						g_acctg_receipts = return_data.acctg_receipts;
						g_acctg_receipt_details = return_data.acctg_receipt_details;
						
						//Compose html
						var html_acctg_receipts = "<table class='no-style-no-border full'  style='margin:15px 5px 0px 5px'>";
						html_acctg_receipts += "<tbody><tr><td colspan='2'><label>Receipt Used in Transaction</label></td></tr>";
						//alert(html_acctg_receipts);
						
						for( acctg_receipt_id in return_data.acctg_receipts ) {
							//Set accounting receipt name
							acctg_receipt_name = return_data.acctg_receipts[acctg_receipt_id];
							acctg_receipt_name_dashed = acctg_receipt_name.toLowerCase().replace(" ", "-");
							html_acctg_receipts += "<tr><td><label class='choice'>";
							html_acctg_receipts += "<input class='receipt-"+ acctg_receipt_name_dashed +"' type='radio' value='"+ acctg_receipt_id +"' /> " + acctg_receipt_name;	
							html_acctg_receipts += "</label></td>";  
							
							//Set accounting receipt details
							html_acctg_receipts += "<td><div class='receipt-"+ acctg_receipt_name.toLowerCase().replace(" ", "-") +"-details hidden'>";
							for( acctg_receipt_detail_id in return_data.acctg_receipt_details[acctg_receipt_id] ) {
								for( acctg_receipt_detail_name in return_data.acctg_receipt_details[acctg_receipt_id][acctg_receipt_detail_id]) {
									acctg_receipt_detail_name_underscored = acctg_receipt_detail_name.toLowerCase().replace(" ", "_");
									acctg_receipt_detail_type = return_data.acctg_receipt_details[acctg_receipt_id][acctg_receipt_detail_id][acctg_receipt_detail_name];
									//Details will be displayed based on its type
									if( acctg_receipt_detail_type == 'text' ) {
										html_acctg_receipts += "<input type='text' class='field-receipt-detail-"+ acctg_receipt_detail_id +"' value='"+ acctg_receipt_detail_name +"' /><br />";
									}
									else if( acctg_receipt_detail_type == 'checkbox' ) {
										html_acctg_receipts += "<label class='choice'><input type='checkbox' class='checkbox-receipt-detail-"+ acctg_receipt_detail_id +"' />"+ acctg_receipt_detail_name +"</label><br />";
									}
								}
							}
							html_acctg_receipts += "</div></td></tr>";
						}
						html_acctg_receipts += "</tbody></table>";
						
						//Display html
						$('.transaction-receipts').html(html_acctg_receipts);
						
						//Transaction Identifiers
						var html_transaction_identifiers = " <select class='select-identifier full'>";
						html_transaction_identifiers += "<option value='-1'>Select Identifier</option>";
						for (id in return_data.transaction_identifiers) {
							html_transaction_identifiers += "<option value='"+ id +"'>"+ return_data.transaction_identifiers[id] +"</option>";
						}
						html_transaction_identifiers += "</select>";
						$('.select-transaction-identifier').html(html_transaction_identifiers);	
						
						//Show entry form
						$('#accounting-entry-form-box').show('slow');
						$('.button-create-entry .loader').hide();
						
					} else {
						ACCOUNTING.show_error_message('Error occured. No data is retrieved.');
					}
				},
				error: function() {
					ACCOUNTING.show_error_message('No entry matched the specified PO # or RFQ #.');
				}
			});			
		}
		
		//return false so that the href of the button will not be followed
		return false;

	});
	
	//Compose data and send to server for saving
	var compose_data = function() {
		
		//hide notification box
		COMMON.hide_notification('#message-box');
		
		//prepare the data to be sent
		var account_group_id = $('.select-accounts option:selected').val();
		var form_data = {};
		form_data['work_id'] = $('.field-work-id').val();
		form_data['description'] = $('.field-description').val();
		form_data['acctg_account_id'] = $('.'+ account_group_id +' option:selected').val();		
		
		//get data for each transaction
		var transactions = {};
		var transaction_id = "";
		var payment_method = "";
		var transaction_receipt = "";
		var tmp = "";
		$('.transactions').find('.transaction').each( function(){
			//get transaction id
			transaction_id = $(this).closest('div').attr('id');
			
			//get transaction data
			transactions[transaction_id] = {};
			
			//get transaction date
			//TODO
			tmp = $('#field-transaction-date_' + transaction_id).val().split("/");
			transactions[transaction_id]['transaction_date'] = "" + tmp[2] + "-" + tmp[1] + "-" + tmp[0];    //yyyy-mm-dd
			
			if( transaction_id.search('MONEY_IN_') == 0 ||
			    transaction_id.search('MONEY_OUT_') == 0 ) {
			
				//amount
				transactions[transaction_id]['amount_before_vat'] = $('#field-amount-before-vat_' + transaction_id).val();
				transactions[transaction_id]['vat'] = $('#field-vat_' + transaction_id).val();
				transactions[transaction_id]['withholding_tax'] = $('#field-withholding-tax_' + transaction_id).val();
				transactions[transaction_id]['total_amount'] = $('#field-total-amount_' + transaction_id).val();
				
				//payment method
				payment_method_id = $("input:radio[name='payment_method_" + transaction_id + "']:checked").val();			
				transactions[transaction_id]['payment_method_id'] = payment_method_id;
				
				//payment method details
				transactions[transaction_id]['payment_method_details'] = {};
				for( payment_method_detail_id in g_payment_method_details[payment_method_id] ) {
					transactions[transaction_id]['payment_method_details'][payment_method_detail_id] = $('#field-method-detail-' + payment_method_detail_id + '_' + transaction_id).val();
				}
			}
			
			//transaction receipt
			acctg_receipt_id = $("input:radio[name='acctg_receipt_" + transaction_id + "']:checked").val();
			transactions[transaction_id]['acctg_receipt_id'] = acctg_receipt_id;
			//alert(transactions[transaction_id]['acctg_receipt_id']);
			
			//transacion receipt details
			transactions[transaction_id]['acctg_receipt_details'] = {};
			for( acctg_receipt_detail_id in g_acctg_receipt_details[acctg_receipt_id] ) {
				for( acctg_receipt_detail_name in g_acctg_receipt_details[acctg_receipt_id][acctg_receipt_detail_id]) {
					acctg_receipt_detail_type = g_acctg_receipt_details[acctg_receipt_id][acctg_receipt_detail_id][acctg_receipt_detail_name];
					
					//Set value based on type
					if( acctg_receipt_detail_type == 'text' ) {
						transactions[transaction_id]['acctg_receipt_details'][acctg_receipt_detail_id] = $('#field-receipt-detail-' + acctg_receipt_detail_id + '_' + transaction_id).val();
					}
					else if( acctg_receipt_detail_type == 'checkbox' ) {
						value = "n";    //unchecked
						if( $('#checkbox-receipt-detail-' + acctg_receipt_detail_id + '_' + transaction_id).is(':checked') ) {
							value = "y";     //checked
						}
						transactions[transaction_id]['acctg_receipt_details'][acctg_receipt_detail_id] = value;
					}
				}				
			}
			
			//attachment
//			var filename = $("#file-attachment_" + transaction_id).val();
//			transactions[transaction_id]['attachment'] = "attachment_" + transaction_id; //getNameFromPath(filename);
//			alert(transactions[transaction_id]['attachment']);
			
			//identifier
			transactions[transaction_id]['identifier_id'] = $("#select-identifier_" + transaction_id +" option:selected").val();
			
			//notes
			transactions[transaction_id]['notes'] = $('#field-transaction-note_' + transaction_id).val();			
		});
		form_data['transactions'] = transactions;
		form_data = { 'json':JSON.stringify(form_data) }
		console.log(form_data);
		
		return form_data;
	}
	
	//Save New Entry
	$(".icon-save-entry").click(function() {

		//show "loading" animation
		$('.icon-save-entry-box .loader').show();	
		
		//compose data and send
		var form_data = compose_data();
		
		//send the data
		$.ajax({
			type: 'POST',
			url: COMMON.base_url + 'accounting/save_entry',
			data: form_data,
			dataType: 'json',
			success: function(return_data) {
				if (return_data=='1') {
					//TODO: Redirect to entries? or notify success?
					console.log(return_data);
					//ACCOUNTING.show_info_message('Entry successfully added.');
					//var message = 'Entry successfully added.';
					//hide "loading" animation
					window.location = COMMON.base_url + "accounting/entries";
				} else {
					ACCOUNTING.show_error_message('Error occured while accessing the database.');
				}
			},
			error: function() {
				ACCOUNTING.show_error_message('Error occured while accessing the database.');
			}
		});
				
		//return false so that the href of the button will not be followed
		return false;
		
	});
	
	$("#button-save-entry").click(function(){

		//show "loading" animation
		$('.button-save-entry-box .loader').show();		
		
		//compose data and send
		var form_data = compose_data();		
		
		//send the data
		$.ajax({
			type: 'POST',
			url: COMMON.base_url + 'accounting/save_entry',
			data: form_data,
			dataType: 'json',
			success: function(return_data) {
				if (return_data=='1') {
					//TODO: Redirect to entries? or notify success?
					console.log(return_data);
					//ACCOUNTING.show_info_message('Entry successfully added.');
					//window.location = COMMON.base_url + "accounting/entries('New accounting entry has been successfully added.')";
					//var message = 'Entry successfully added.';
					//hide "loading" animation
					window.location = COMMON.base_url + "accounting/entries";
				} else {
					ACCOUNTING.show_error_message('Error occured while accessing the database.');
					$('.button-save-entry-box .loader').hide();
				}
			},
			error: function() {
				ACCOUNTING.show_error_message('Error occured while accessing the database.');
				$('.button-save-entry-box .loader').hide();
			}
		});
				
		//return false so that the href of the button will not be followed
		return false;
		
	});
	
	 
	/****************** Entries View Functions ******************/
	
	//filters
	$(".field-from-date").datepick();
	$(".field-to-date").datepick();
	
		
	/****************** Entries View Functions ******************/
	
		$(".button-edit-entry").click(function() {
			var elementId = $(this).attr("id");	
			elementId = elementId.substring(elementId.indexOf("_")+1);
			//alert(elementId);
			
			var form_data = {};
			//send the data
			$.ajax({
				type: 'POST',
				url: COMMON.base_url + 'accounting/edit_entry/' + elementId,
				data: form_data,
				dataType: 'json',
				success: function(return_data) {
					if (return_data) {
						//TODO: Redirect to entries? or notify success?
						console.log(return_data);
						
						//ACCOUNTING.show_info_message('Entry successfully updated.');
						//window.location = COMMON.base_url + "accounting/entries('New accounting entry has been successfully added.')";
					} else {
						ACCOUNTING.show_error_message('Error occured while accessing the database.');
					}
				},
				error: function() {
					ACCOUNTING.show_error_message('Error occured while accessing the database.');
				}
			});
					
			//return false so that the href of the button will not be followed
			return false;
		});
	
		$("#button-save-edit-entry").click(function(){
		
			//compose data and send
			var form_data = compose_data();
			
			//send the data
			$.ajax({
				type: 'POST',
				url: COMMON.base_url + 'accounting/update_entry/' + $('.field-acctg-entry-id').val(),
				data: form_data,
				dataType: 'json',
				success: function(return_data) {
					if (return_data=='1') {
						//TODO: Redirect to entries? or notify success?
						console.log(return_data);
						ACCOUNTING.show_info_message('Entry successfully updated.');
						//window.location = COMMON.base_url + "accounting/entries('New accounting entry has been successfully added.')";
					} else {
						ACCOUNTING.show_error_message('Error occured while accessing the database.');
					}
				},
				error: function() {
					ACCOUNTING.show_error_message('Error occured while accessing the database.');
				}
			});
					
			//return false so that the href of the button will not be followed
			return false;		
		});
	
	
	/****************** Reports View Functions ******************/
		
	$("#create-report").click(function(){
			$("#report-quick-view").show('slow');
  	});
	
	$("#clear-report").click(function(){
			$("#report-quick-view").hide('slow');
  	});	
	
	
	/****************** Utilities Functions ******************/
	
	function getNameFromPath(strFilepath) {
		var objRE = new RegExp(/([^\/\\]+)$/);
		var strName = objRE.exec(strFilepath);
	 
		if (strName == null) {
			return null;
		}
		else {
			return strName[0];
		}
	}

});